package org.ccay.ws.databind;

import java.io.IOException;

import org.ccay.enumerable.EnumItem;
import org.ccay.enumerable.EnumUtil;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.JsonToken;
import org.codehaus.jackson.map.DeserializationContext;
import org.codehaus.jackson.map.annotate.JsonCachable;
import org.codehaus.jackson.map.deser.StdScalarDeserializer;

@JsonCachable
public class EnumItemDeserializer<T> extends StdScalarDeserializer<EnumItem<?>> {

	private String enumType;
	
	protected EnumItemDeserializer(Class<?> vc,String enumType) {
		super(vc);
		this.enumType = enumType;
	}

	@Override
	public EnumItem<?> deserialize(JsonParser jp, DeserializationContext ctxt)
			throws IOException, JsonProcessingException {
		JsonToken curr = jp.getCurrentToken();
		if (curr == JsonToken.VALUE_STRING || curr == JsonToken.VALUE_NUMBER_INT) {
			String value = jp.getText();
			EnumItem<?> result = EnumUtil.getInstance().getByTypeValue(enumType, value);
			if (result == null) {
				throw ctxt.weirdStringException(getValueClass(), "value not one of declared Enum instance names");
			}
			return result;
		}
		throw ctxt.mappingException(getValueClass());
	}

}
